package ms.platform.plan.service;

import ms.platform.common.exception.BusinessException;
import ms.platform.plan.dao.BusModelDao;
import ms.platform.plan.dao.BusModelMeterPlanDao;
import ms.platform.plan.dao.BusModelPlanDao;
import ms.platform.plan.dto.ModelDto;
import ms.platform.plan.model.ModelMeterPlan;
import ms.platform.plan.model.ModelPlan;
import ms.platform.progress.dao.FactoryPlanDao;
import ms.platform.progress.dto.ProgressDto;
import ms.platform.util.DateUtil;
import ms.platform.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class ModelPlanMeterService {

    @Autowired
    BusModelPlanDao busModelPlanDao;
    @Autowired
    BusModelMeterPlanDao busModelMeterPlanDao;
    @Autowired
    FactoryPlanDao factoryPlanDao;
    @Autowired
    BusModelDao busModelDao;

    /**
     * 带条件分页查询list
     *
     * @param map
     * @return
     */
    public List<ModelPlan> queryPageBusModelPlanList(Map<String, Object> map) {
        return busModelPlanDao.queryPageBusModelPlanList(map);
    }

    /**
     * 分页查询获取总条数
     *
     * @param map
     * @return
     */
    public Integer queryBusModelPlanCount(Map<String, Object> map) {
        return busModelPlanDao.queryBusModelPlanCount(map);
    }

    /**
     * 计划下发
     *
     * @return
     */
    public void updateModelPlanStatusForEffective(ModelPlan model) {
        ModelDto mp = busModelDao.queryBusModelById(model.getModelId());
        Date planStartTime = mp.getPlanStartTime();
        Date planEndTime = mp.getPlanEndTime();
        Date d = new Date(planStartTime.getTime());
        long longPlanEndTime = planEndTime.getTime();
        long longd = d.getTime();
        Map<String, Object> map = new HashMap<>();
        map.put("id", mp.getModelPlanId());
        map.put("startTime", d);
        System.out.println("Id:" + map.get("id"));
        System.out.println("startTime:" + d);
        List<ModelPlan> modelPlan = busModelPlanDao.queryModelPlanInfoById(map);

        while (d.getTime() <= longPlanEndTime) {
        	if(modelPlan.size()>1){
        		for (ModelPlan _modelPlan : modelPlan) {
        			ProgressDto dto = new ProgressDto();
        			dto.setModelId(_modelPlan.getModelId());
                    dto.setModelPlanId(_modelPlan.getId());
                    dto.setModelCode(_modelPlan.getModelCode());
                    dto.setReportDate(DateUtil.getDateString(d, "yyyy-MM-dd"));
                    dto.setPlanProcessId(_modelPlan.getModelProcessId());
                    dto.setPlanProcessName(_modelPlan.getModelProcessName());
                    dto.setExtDay("0");
                    dto.setStatus("-1");
                    factoryPlanDao.saveProgressRecord(dto);
				}
        		d = DateUtil.addDate(d, 1);
                longd = d.getTime();
                map.put("startTime", d);
                modelPlan = busModelPlanDao.queryModelPlanInfoById(map);
        	}else{
        		ModelPlan _modelPlan = modelPlan.get(0);
        		ProgressDto dto = new ProgressDto();
                dto.setModelId(_modelPlan.getModelId());
                dto.setModelPlanId(_modelPlan.getId());
                dto.setModelCode(_modelPlan.getModelCode());
                dto.setReportDate(DateUtil.getDateString(d, "yyyy-MM-dd"));
                if (_modelPlan.getPlanStartTime().getTime() <= longd && _modelPlan.getPlanEndTime().getTime() > longd) {
                    dto.setPlanProcessId(_modelPlan.getModelProcessId());
                    dto.setPlanProcessName(_modelPlan.getModelProcessName());
                } else {
                    map.put("startTime", d);
                    modelPlan = busModelPlanDao.queryModelPlanInfoById(map);
                    if (modelPlan == null || modelPlan.size() == 0) {
                        break;
                    }
                    dto.setPlanProcessId(modelPlan.get(0).getModelProcessId());
                    dto.setPlanProcessName(modelPlan.get(0).getModelProcessName());
                }
                dto.setExtDay("0");
                dto.setStatus("-1");
                factoryPlanDao.saveProgressRecord(dto);
                d = DateUtil.addDate(d, 1);
                longd = d.getTime();
        	}
        }
        //更改计划状态为下发
        busModelPlanDao.updateModelPlanStatusById(model);
    }

    /**
     * 根据id 修改计划状态
     *
     * @return
     */
    public void updateModelPlanStatusById(ModelPlan model) {
        busModelPlanDao.updateModelPlanStatusById(model);
    }

    /**
     * 材料信息新增
     *
     * @param modelMeterPlan
     * @return
     */
    public void saveBusModelMeterPlan(ModelMeterPlan modelMeterPlan) {
        busModelMeterPlanDao.saveBusModelMeterPlanFinished(modelMeterPlan);
    }

    /**
     * 带条件分页查询list
     *
     * @param map
     * @return
     */
    public List<ModelMeterPlan> queryPageBusModelMeterList(Map<String, Object> map) {
        return busModelMeterPlanDao.queryPageBusModelMeterList(map);
    }

    /**
     * 分页查询获取总条数
     *
     * @param map
     * @return
     */
    public Integer queryBusModelMeterCount(Map<String, Object> map) {
        return busModelMeterPlanDao.queryBusModelMeterCount(map);
    }

    /**
     * 根据模具番号统计剩余库存
     *
     * @param modelCode
     * @return
     */
    public Integer sumInventoryByModelCode(String modelCode) {
        return busModelMeterPlanDao.sumInventoryByModelCode(modelCode);
    }

    /**
     * 根据模具番号查询部品明细
     *
     * @param modelCode
     * @return
     */
    public ModelMeterPlan getMeterInfoByModelCode(String modelCode) {
        return busModelMeterPlanDao.getMeterInfoByModelCode(modelCode);
    }

    /**
     * 带条件分页查询list
     *
     * @param map
     * @return
     */
    public List<ModelMeterPlan> queryPageBusModelAllMeterList(Map<String, Object> map) {
        return busModelMeterPlanDao.queryPageBusModelAllMeterList(map);
    }

    /**
     * 分页查询获取总条数
     *
     * @param map
     * @return
     */
    public Integer queryBusModelAllMeterCount(Map<String, Object> map) {
        return busModelMeterPlanDao.queryBusModelAllMeterCount(map);
    }

    /**
     * 根据模具番号查询入库材料信息
     *
     * @param modelCode
     * @return
     */
    public List<ModelMeterPlan> queryModelMeterPlanFinished(String modelCode) {
        return busModelMeterPlanDao.queryModelMeterPlanFinished(modelCode);
    }

    /**
     * 修改库存量
     *
     * @param modelMeterPlan
     */
    public void updateInventory(ModelMeterPlan modelMeterPlan) {
        Integer planNum = modelMeterPlan.getPlanNum();
        List<ModelMeterPlan> modelMeterPlanList = busModelMeterPlanDao.queryModelMeterPlanFinished(modelMeterPlan.getModelCode());
        for (ModelMeterPlan modelMeter : modelMeterPlanList) {
            Map<String, Object> map = new HashMap<String, Object>();
            if (planNum > 0) {
                if (planNum > modelMeter.getAvaliablAmount()) {
                    map.put("id", modelMeter.getId());
                    map.put("avaliablAmount", 0);
                    busModelMeterPlanDao.updateModelMeterAvaliablAmount(map);
                    planNum = planNum - modelMeter.getAvaliablAmount();
                } else {
                    map.put("id", modelMeter.getId());
                    map.put("avaliablAmount", modelMeter.getAvaliablAmount() - planNum);
                    busModelMeterPlanDao.updateModelMeterAvaliablAmount(map);
                    planNum = 0;
                }
            } else if (planNum == 0) {
                break;
            } else {
                throw new BusinessException("总库存数小于支给数");
            }

        }
    }

    /**
     * 根据部品番号查询材料信息
     *
     * @param modelCode
     * @return
     */
    public ModelMeterPlan queryMeterInfoByModelCode(String modelCode) {
        return busModelMeterPlanDao.getMeterInfoByModelCode(modelCode);
    }

    /**
     * 下发信息新增
     *
     * @param modelMeterPlan
     * @return
     */
    public void saveBusMeterGiveRecord(ModelMeterPlan modelMeterPlan) {
        busModelMeterPlanDao.saveBusMeterGiveRecord(modelMeterPlan);
    }

    /**
     * 材料下发列表
     *
     * @return
     */
    public List<ModelMeterPlan> getMeterGiveRecord(Map<String, Object> map, HttpServletRequest request, String userId) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("userId", userId);
        map.put("userId", userId);
        Integer counts = busModelMeterPlanDao.getMeterGiveRecordCount(map);
        map.put("count", counts == null ? 0 : counts);
        List<ModelMeterPlan> list = busModelMeterPlanDao.getMeterGiveRecord(PageUtils.Page(request, map));
        for (ModelMeterPlan modelMeterPlan : list) {
            maps.put("modelCode", modelMeterPlan.getModelCode());
            Integer usedAmount = busModelMeterPlanDao.getMeterUsedAmount(maps);
            modelMeterPlan.setUserAmount(usedAmount);
        }
        PageUtils.calculate(map);
        return list;
    }

    public ModelMeterPlan getMeterInfoById(String id, String userId) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("userId", userId);
        ModelMeterPlan modelMeterPlan = busModelMeterPlanDao.getMeterInfoById(id);
        if (null != modelMeterPlan && null != modelMeterPlan.getModelCode()) {
            maps.put("modelCode", modelMeterPlan.getModelCode());
            Integer inventory = busModelMeterPlanDao.getMeterGiveAmount(maps);
            Integer usedAmount = busModelMeterPlanDao.getMeterUsedAmount(maps);
            modelMeterPlan.setAvaliablAmount(inventory - (usedAmount == null ? 0 : usedAmount));
        }
        return modelMeterPlan;
    }

    /**
     * 获取只给详情
     */
    public List<ModelMeterPlan> getLssuedDetails(Integer modelPlanId) {
        return busModelMeterPlanDao.getLssuedDetails(modelPlanId);
    }

    public ModelMeterPlan getLssuedDetailsToEdit(Integer id) {
        return busModelMeterPlanDao.getLssuedDetailsToEdit(id);
    }

    public void updateLssuedDetails(ModelMeterPlan modelMeterPlan) {
        busModelMeterPlanDao.updateLssuedDetails(modelMeterPlan);
    }
    /**
     * 查询材料信息
     * @param id
     * @return
     */
    public ModelMeterPlan queryMeterInfoById(Integer id) {
        return busModelMeterPlanDao.queryMeterInfoById(id);
    }
    /**
     * 修改材料信息
     * @param modelMeterPlan
     */
    public void editMeterInfoById(ModelMeterPlan modelMeterPlan) {
        busModelMeterPlanDao.editMeterInfoById(modelMeterPlan);
    }
    /**
	 * 根据材料id修改材料信息
	 * @param id
	 * @return
	 */
	public void editMeterPlanByMeterId(ModelMeterPlan modelMeterPlan){
		busModelMeterPlanDao.editMeterPlanByMeterId(modelMeterPlan);
	}
	/**
	 * 根据材料id修改材料下发信息
	 * @param id
	 * @return
	 */
	public void editMeterGiveByMeterId(ModelMeterPlan modelMeterPlan){
		busModelMeterPlanDao.editMeterGiveByMeterId(modelMeterPlan);
	}
}
